package com.hqk.flowpractice.viewmodel

import android.app.Application
import android.app.Service
import android.content.Context
import android.os.Vibrator
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.hqk.flowpractice.model.Article
import com.hqk.flowpractice.net.RetrofitClient
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.launch


class ArticleViewModel : AndroidViewModel {

    var app: Application? = null

    constructor(app: Application) : super(app) {
        this.app = app
    }

    val articles = MutableLiveData<List<Article>>()

    fun searchArticles(key: String) {

        viewModelScope.launch {
            flow {
                val list = RetrofitClient.articleApi.searchArticles(key)
                emit(list)
            }.flowOn(Dispatchers.IO)
                .catch { e -> e.printStackTrace() }
                .collect {
                    articles.setValue(it)
                }
        }
    }


}

